﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Bingosoft.Components.DataDictionary;
using System.Data;
using System.Web.UI;
using Bingosoft.Data;

namespace HHMMS.Core.WebControls
{
    public class SmartDropDownList : DropDownList
    {
        // Properties
        [PersistenceMode(PersistenceMode.Attribute)]
        public string CommandName { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public string DictionaryCode { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public string EmptyItemText { get; set; }

        [PersistenceMode(PersistenceMode.Attribute)]
        public bool IncludedEmptyItem { get; set; }

        public SmartDropDownList()
        {
            this.IncludedEmptyItem = true;
            this.EmptyItemText = "--请选择--";
        }

        protected override void TrackViewState()
        {
            base.TrackViewState();
            if (!this.Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(this.DictionaryCode))
                {
                    IEnumerable<KeyValuePair<string, string>> lists = DataDictionaryFactory.DataDictionaryProvider.LookupDataDictionary(this.DictionaryCode);
                    foreach (KeyValuePair<string, string> item in lists)
                    {
                        this.Items.Add(new ListItem(item.Value, item.Key));
                    }
                }
                else if (!string.IsNullOrEmpty(this.CommandName))
                {
                    IDataReader reader = Dao.Get().QueryReader(this.CommandName, null);
                    while (reader.Read())
                    {
                        if (!(string.IsNullOrEmpty(this.DataTextField) || string.IsNullOrEmpty(this.DataValueField)))
                        {
                            this.Items.Add(new ListItem(Convert.ToString(reader.GetValue(reader.GetOrdinal(this.DataTextField))), Convert.ToString(reader.GetValue(reader.GetOrdinal(this.DataValueField)))));
                        }
                        else
                        {
                            this.Items.Add(new ListItem(Convert.ToString(reader.GetValue(0)), Convert.ToString(reader.GetValue(1))));
                        }
                    }
                }
                if (this.IncludedEmptyItem)
                {
                    this.Items.Insert(0, new ListItem(this.EmptyItemText, string.Empty));
                }
            }
        }
    }
}
